<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { useDictStore } from '@/store/modules/dictData'
import { Icon } from '@/components/Icon'
import { ref, unref, reactive, h, computed } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import PatrolInfoApi from '@/api/linePatrol'
import TaskDetail from '@/views/linePatrol/InspectionTasks/components/TaskDetail.vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElTag, ElSelect, ElOption } from 'element-plus'
import SetSecurCheckApi from '@/api/securcheck/SetSecurCheck'
import { PatrolPlanListType } from '@/api/linePatrol/type'
//引入安装的依赖
import * as XLSX from 'xlsx'
import { usePatrolGroupStore } from '@/store/modules/PlanGroupStore'
const ids = ref<string[]>([])
const { query } = useRoute()
const { go } = useRouter()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    let i = {} as any
    if (Number(query.groupUserCom) == 3) {
      i = await PatrolInfoApi.PatrolplanList({
        pageNum: unref(currentPage),
        pageSize: unref(pageSize),
        taskName: String(query.taskName),
        ...unref(searchParams)
      })
    } else {
      i = await SetSecurCheckApi.SecurPlanList({
        pageNum: unref(currentPage),
        pageSize: unref(pageSize),
        taskName: String(query.taskName),
        groupUserCom: Number(query.groupUserCom),
        ...unref(searchParams)
      })
    }
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = ref()
    if (Number(query.groupUserCom) == 3) {
      res.value = await PatrolInfoApi.DeletPatrolplan(unref(ids)[0])
    } else {
      res.value = await SetSecurCheckApi.DeletSecurplan(unref(ids)[0])
    }
    return !!res.value
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const DictStore = useDictStore()
//获取字典
// secur_group_type
DictStore.setDict('secur_group_type') //状态字典
DictStore.setDict('task_state') //状态字典
DictStore.setDict('fac_task_type') //巡检任务状态字典
DictStore.setDict('task_ioan_state') //检查状态字典
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'taskState',
    label: t('状态'),
    width: '120px',
    search: {
      hidden: false,
      component: 'Select',
      componentProps: {
        placeholder: '状态',
        options: DictStore.$state.task_state?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      }
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.task_state?.map((item) => {
        if (item.dictValue == cellValue) {
          return h(ElTag, { type: item.listClass }, () => t(item.dictLabel))
        }
      })
    },
    detail: {
      slots: {
        default: (data: any) => {
          return DictStore.$state.task_state?.map((item) => {
            if (item.dictValue == data.taskState) {
              return <ElTag type={item.listClass}>{t(item.dictLabel)}</ElTag>
            }
          })
        }
      }
    }
  },
  {
    field: 'taskType',
    label: t('任务类型'),
    formatter: (_: Recordable, __: any, cellValue: string) => {
      if (Number(query.groupUserCom) == 3) {
        return DictStore.$state.fac_task_type?.map((item) => {
          if (item.dictValue == cellValue) {
            return t(item.dictLabel)
          }
        })
      } else {
        return DictStore.$state.secur_group_type?.map((item) => {
          if (item.dictValue == cellValue) {
            return t(item.dictLabel)
          }
        })
      }
    },
    search: {
      hidden: true
    },
    detail: {
      slots: {
        default: (data: PatrolPlanListType) => {
          if (Number(query.groupUserCom) == 3) {
            return DictStore.$state.fac_task_type?.map((item) => {
              if (item.dictValue == data.taskType) {
                return <ElTag type={item.listClass}>{t(item.dictLabel)}</ElTag>
              }
            })
          } else {
            return DictStore.$state.secur_group_type?.map((item) => {
              if (item.dictValue == data.taskType) {
                return <ElTag type={item.listClass}>{t(item.dictLabel)}</ElTag>
              }
            })
          }
        }
      }
    }
  },
  {
    field: 'facName',
    label: t('任务名称'),
    search: {
      hidden: true
    },
    table: {
      hidden: Number(query.groupUserCom) == 3 ? false : true
    },
    detail: {
      hidden: Number(query.groupUserCom) == 3 ? false : true
    }
  },
  {
    field: 'name',
    label: t('任务名称'),
    search: {
      hidden: true
    },
    table: {
      hidden: Number(query.groupUserCom) == 3 ? true : false
    },
    detail: {
      hidden: Number(query.groupUserCom) == 3 ? true : false
    }
  },
  {
    field: 'planName',
    width: 100,
    label: t('所属计划'),
    search: {
      hidden: true
    }
  },
  {
    field: 'taskName',
    width: 150,
    label: t('所属周期'),
    search: {
      hidden: true
    }
  },
  {
    field: 'faciName',
    width: 100,
    label: t('类型'),
    search: {
      hidden: true
    },
    table: {
      hidden: Number(query.groupUserCom) == 3 ? false : true
    },
    detail: {
      hidden: Number(query.groupUserCom) == 3 ? false : true
    }
  },
  {
    field: 'executeUser',
    width: 100,
    label: t('执行对象'),
    search: {
      hidden: true
    }
  },
  {
    field: 'finishUser',
    width: 100,
    label: t('完成人'),
    search: {
      hidden: true
    }
  },
  {
    field: 'finishDate',
    label: t('完成时间'),
    width: 150,
    search: {
      hidden: true
    }
  },
  {
    field: 'passRate',
    width: 100,
    label: t('检查人'),
    search: {
      hidden: true
    }
  },
  {
    field: 'inspectDate',
    width: 150,
    label: t('检查时间'),
    search: {
      hidden: true
    }
  },
  {
    field: 'inspectState',
    width: 120,
    label: t('检查状态'),
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.task_ioan_state?.map((item) => {
        if (item.dictValue == cellValue) {
          return h(ElTag, { type: item.listClass }, () => t(item.dictLabel))
        }
      })
    },
    detail: {
      slots: {
        default: (data: PatrolPlanListType) => {
          return DictStore.$state.task_ioan_state?.map((item) => {
            if (item.dictValue == data.inspectState) {
              return <ElTag type={item.listClass}>{t(item.dictLabel)}</ElTag>
            }
          })
        }
      }
    }
  },
  {
    field: 'taskDesc',
    label: t('任务描述'),
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'taskFile',
    label: t('任务附件'),
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    detail: {
      hidden: Number(query.groupUserCom) == 3 ? false : true
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 200,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          if (Number(query.groupUserCom) == 3) {
            return (
              <>
                <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
                  {t('查看')}
                </span>
                <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                  {t('删除')}
                </span>
              </>
            )
          } else {
            return (
              <>
                <span class="TableBtn" onClick={() => action(data.row, 'Detail')}>
                  {t('查看')}
                </span>
                <span class="TableBtn" onClick={() => action(data.row, 'TransferOffice')}>
                  {t('转办')}
                </span>
                <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                  {t('删除')}
                </span>
              </>
            )
          }
        }
      }
    }
  }
])
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
const delLoading = ref(false)
//删除
const delData = async (row: PatrolPlanListType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.uuid]
    : elTableExpose?.getSelectionRows().map((v: PatrolPlanListType) => v.uuid) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const dialogVisible = ref(false)
const currentRow = ref<PatrolPlanListType>({})
const actionType = ref('')
const TransferOffice = ref(false)
//表格操作
const action = async (row: PatrolPlanListType, type: string) => {
  currentRow.value = row
  actionType.value = type
  if (type == 'TransferOffice') {
    TransferOffice.value = true
  } else {
    dialogVisible.value = true //打开弹窗
    const res = await SetSecurCheckApi.SecurHdtemplate(row.uuid)
    console.log(res)
  }
  // log
}
//巡检任务表格导出excel
const ExportTableData = () => {
  const workbook = XLSX.utils.book_new()
  //在table上建立的id属性
  const ws1 = XLSX.utils.table_to_sheet(document.getElementById('table'))
  XLSX.utils.book_append_sheet(workbook, ws1, 'Sheet1')
  XLSX.writeFile(workbook, `巡检任务.xlsx`)
}
//批量选择
const handleSelectionChange = (val) => {
  console.log(val)
}
const GroupStore = usePatrolGroupStore()
const UserList = computed(() => {
  return GroupStore.getUserListAll
}) //执行用户列表
const title = ref(`任务列表--${query.taskName}周期`)
const SelectValue = ref<string>('')
const saveLoading = ref(false)
const save = async () => {
  saveLoading.value = true
  const res = await SetSecurCheckApi.SecurPlanHandover({
    uuid: currentRow.value.uuid,
    executeUser: SelectValue.value
  })
  if (res) {
    getList()
    saveLoading.value = false
    TransferOffice.value = false
    ElMessage({
      message: '转办成功',
      type: 'success'
    })
  } else {
    ElMessage({
      message: '转办成功',
      type: 'error'
    })
  }
}
</script>

<template>
  <ContentWrap style="position: relative" :title="title">
    <BaseButton size="small" class="ExportBtn" type="primary" @click="go(-1)">
      <Icon icon="ep:back" :size="12" />
      {{ t('返回') }}
    </BaseButton>
    <BaseButton size="small" type="primary" class="ExportBtn" @click="ExportTableData">
      <Icon icon="ep:download" :size="12" />导出
    </BaseButton>
    <Search
      class="ExportBtn"
      :schema="allSchemas.searchSchema"
      :inline="true"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <Table
      id="table"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      row-key="uuid"
      :pagination="{
        total: total
      }"
      @selection-change="handleSelectionChange"
      @register="tableRegister"
    />
  </ContentWrap>
  <Dialog
    v-model="TransferOffice"
    style="width: 500px; margin-top: -250px !important"
    maxHeight="80px"
    title="转办详情"
  >
    选择责任人：
    <ElSelect v-model="SelectValue" placeholder="Select" style="width: 340px">
      <ElOption
        v-for="item in UserList"
        :key="item.userName"
        :label="item.userName"
        :value="item.userName"
      />
    </ElSelect>
    <template #footer>
      <BaseButton type="primary" :loading="saveLoading" @click="save">
        {{ t('提交') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
    </template>
  </Dialog>
  <Dialog v-model="dialogVisible" title="任务详情">
    <TaskDetail
      ref="EditDictTypeRef"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    />
  </Dialog>
</template>
<style scoped lang="less">
.el-form {
  display: inline-block;
  margin-left: 15px;
}

.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}
.ExportBtn {
  margin-top: -15px;
  margin-right: 10px;
}

.el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
  text-align: center;
}
.TableBtn {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
